package com.xxxx;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * 批量数据处理
 */
public class WordCountBatchByJava {
    public static void main(String[] args) throws Exception {
        //获取执行环境
        ExecutionEnvironment environment = ExecutionEnvironment.getExecutionEnvironment();
        //获取数据源
        DataSource<String> source = environment.readTextFile("data/dataset.txt");
        //开始进行转换--Map单行函数
        //source.map(line -> line + "aa").print();
        //开始进行转换--Count组函数
        //System.out.println(source.count());
        //1.开始进行转换-- String(hello moto01) String[hello,moto01]
        FlatMapOperator<String, String> flatMap = source.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, Collector<String> collector) throws Exception {
                String[] words = line.split(" ");
                for (String word : words) {
                    collector.collect(word);
                }
            }
        });
        //2.每一个单词默认赋予一个数量
        MapOperator<String, Tuple2<String, Integer>> map = flatMap.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String word) throws Exception {
                return Tuple2.of(word, 1);
            }
        });
        //3.将数据进行分组
        UnsortedGrouping<Tuple2<String, Integer>> group = map.groupBy(0);
        AggregateOperator<Tuple2<String, Integer>> sum = group.sum(1);
        //4.打印结果
        sum.print();
    }
}
